import Cookies from 'js-cookie'

interface IState {
  sidebar: {
    opened: boolean
    withoutAnimation: boolean
    hide: boolean
  }
  device: string
  size: string
  detailFirstVisit: boolean
}

const state = {
  sidebar: {
    opened: (() => {
      const sidebarStatus = Cookies.get('sidebarStatus')
      return sidebarStatus ? sidebarStatus === '1' : true
    })(),
    withoutAnimation: false,
    hide: false,
  },
  device: 'desktop',
  size: Cookies.get('size') || 'medium',
  detailFirstVisit: true, // 默认是第一次进入
}

const mutations = {
  TOGGLE_SIDEBAR: (state: IState) => {
    if (state.sidebar.hide) {
      return
    }
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', '1')
    } else {
      Cookies.set('sidebarStatus', '0')
    }
  },
  CLOSE_SIDEBAR: (state: IState, withoutAnimation: boolean) => {
    Cookies.set('sidebarStatus', '0')
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state: IState, device: string) => {
    state.device = device
  },
  SET_SIZE: (state: IState, size: string) => {
    state.size = size
    Cookies.set('size', size)
  },
  SET_SIDEBAR_HIDE: (state: IState, status: boolean) => {
    state.sidebar.hide = status
  },
  SET_DETAIL_VISITED(state: IState, value: boolean) {
    state.detailFirstVisit = value
  },
}

type Commit = <T>(type: string, payload?: T) => void

const actions = {
  toggleSideBar({ commit }: { commit: Commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar(
    { commit }: { commit: Commit },
    { withoutAnimation }: { withoutAnimation: boolean },
  ) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }: { commit: Commit }, device: string) {
    commit('TOGGLE_DEVICE', device)
  },
  setSize({ commit }: { commit: Commit }, size: string) {
    commit('SET_SIZE', size)
  },
  toggleSideBarHide({ commit }: { commit: Commit }, status: boolean) {
    commit('SET_SIDEBAR_HIDE', status)
  },
  setDefaultVisit({ commit }: { commit: Commit }, status: boolean) {
    commit('SET_DETAIL_VISITED', status)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
